<template>
  <div> 
      <el-dialog title='新增微信app' 
      :visible.sync='visible' 
      @close="$emit('update:show', false)" 
      :show="show">
      <el-form :model="editingApp" ref="appForm" :rules="rules">
        <el-form-item label='微信APPID' prop="appid">
          <el-input v-model='editingApp.appid' placeholder="请输入微信APPID" :disabled="!editDialogIsNewMode"></el-input>
        </el-form-item>
        <el-form-item label='微信APP名称' prop="appname">
          <el-input v-model='editingApp.appname' placeholder="请输入微信APP名称"></el-input>
        </el-form-item>
         <el-form-item label='Crm网关' prop="crmapigetway">
          <el-input v-model='editingApp.crmapigetway' placeholder="请输入crm卡网关"></el-input>
        </el-form-item>
        <el-form-item label="默认城市" prop="cityadcode">          
            <el-select v-model='selectedProvince' placeholder="请选择" class="input" @change="emtyCity" @visible-change="selectProvince">
                <el-option v-for="(item,index) in mapCategorys" :key="index" :label="item.name" :value="index">
                </el-option>
            </el-select>
            <el-select  v-model='editingApp.cityadcode' placeholder="请选择" class="input">
                <el-option v-for="(item,index) in citys" :key="item.adcode" :label="item.name" :value="item.adcode">
                </el-option>
            </el-select>
        </el-form-item>         
        <el-form-item prop="crmqrcodeurl">    
          <div class="lable-span">领卡二维码</div>     
          <div class="qrcode_img">           
            <el-upload :show-file-list="false" class="qrcode-uploader" :action="uploadUrl" :on-success="uploadQrcodeSuccesss">
              <img v-if="editingApp.crmqrcodeurl!=''" :src="editingApp.crmqrcodeurl" class="qrcode"> </img>
              <div v-else class="deaultqrcode"> </div>
            </el-upload>
          </div>
        </el-form-item>       
        <el-form-item label="首页展示类型" prop="apphometype">
          <el-select v-model="editingApp.apphometype" placeholder="请选择">
            <el-option label="店铺列表" :value="0"> </el-option>
            <el-option label="热卖展示" :value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首页展示店铺" prop="mainshop" v-show="editingApp.apphometype==1">
          <el-select v-model="editingApp.mainshopid" filterable placeholder="请选择">
            <el-option v-for="shop in shopSelectList" :key="shop.shopid" :label="shop.shopname" :value="shop.shopid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="editingApp.apphometype==0">
          <div class="lable-span">首页跑马灯图片</div>
          <div>
            <ul class="img-wrapper">
              <li v-for="(pic,index) in editingApp.swipepics" :key="index">
                <div class="img-container">
                  <img :src="pic" class="avatar"> </img>
                </div>
                <div align="center">
                  <i class="fa fa-times-circle" style="font-size: 24px;color: red;" @click="deleteJpg(index)"></i>
                </div>
              </li>
            </ul>
            <el-upload class="upload-file" :action="uploadUrl" :on-success="uploadSuccess" :show-file-list="false">
              <el-button type="primary">上传
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-upload>
          </div>
        </el-form-item>        
        <el-form-item label='每单最大付款限额' prop="maxorderpaymy">
          <el-input-number v-model="editingApp.maxorderpaymy" :min="0" :controls="true" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label='配送范围(km)' prop="sendrange">
          <el-input-number v-model="editingApp.sendrange" :min="0" :controls="true"></el-input-number>
        </el-form-item>
        <el-form-item>
          <div class="lable-span">快速备注</div>
          <ul>
            <li v-for="(info,index) in editingApp.fixedremarks" :key="index" style="margin-top:12px;margin-bottom:12px;">
              <el-input placeholder="请输入备注" v-model="info.remarkstext">
                <el-button slot="append" icon="close" @click='removeRemarks(index)'></el-button>
              </el-input>
            </li>
          </ul>
          <el-button type="primary" icon="plus" plain size="small" @click='addRemarks'>添加</el-button>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditAppSubmit'>确定</el-button>
        <el-button @click='show = false'>取消</el-button>
      </div>
    </el-dialog>
 </div>
</template>

<script>
import axios from "axios";
import { Utils } from "@/utils/utils.js";

export default {
  data() {
      const validateappexist = (rule, value, callback) => {
      if (this.editDialogIsNewMode) {
        this.$http
          .get("/WechatMallOss/App/GetAppByAppId", {
            params: {
              appid: value
            }
          })
          .then(response => {
            if (response.data.isSuccess) {
              if (response.data.appinfo == null) {
                callback();
              } else {
                callback(new Error("app已存在"));
              }
            } else {
              callback(new Error("验证遇见未知错误!"));
            }
          })
          .catch(err => {
            callback(err);
          });
      } else {
        callback();
      }
    };
    return {
      visible: this.show,
      // 表格数据源
      gridDataSource: [],
      currentSelectedRow: null,
      gridDataIsLoading: false,
      // 编辑窗体的状态是否是新增状态
      editDialogIsNewMode: true,
      // 编辑层是否显示
      editAppDialogOpend: false,
      //  正在编辑的model
      editingApp: {
        appid: "",
        appname: "",
        apphometype: 0,
        maxorderpaymy: 0,
        sendrange: 0,
        swipepics: [],
        cityname: "",
        citycenter: "",
        cityadcode: "",
        mainshopid: 0,
        crmapigetway: "",
        crmqrcodeurl: "",
        fixedremarks: []
      },
      // 编辑的app 下属门店列表
      shopSelectList: [],
      // 表单验证规则
      rules: {
        appid: [
          { required: true, trigger: "blur", message: "微信APPID必填" },
          {
            type: "string",
            max: 50,
            trigger: "blur",
            message: "微信APPID必须小于50个字"
          },
          { trigger: "blur", validator: validateappexist }
        ],
        appname: [
          { required: true, trigger: "blur", message: "微信APP名称必填" },
          {
            type: "string",
            max: 50,
            trigger: "blur",
            message: "微信APP名称必须小于50个字"
          }
        ],
        crmapigetway: [
          { required: true, trigger: "blur", message: "crm卡网关必填" }
        ],
        cityadcode: [{ required: true, trigger: "blur", message: "默认定位城市必选" }],
        crmqrcodeurl: [{ required: true, trigger: "blur", message: "领卡二维码必选！" }]
      },
      // 指定货品
      selecteGoods: [],
      allGoods: [],
      defaultGoodDialogOpend: false,
      mapCategorys: [],
      selectedProvince: '',
      citys: []
    };
  },
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  methods: {
      /**
     * 提交新增app表单
     */
    handleEditAppSubmit() {
      this.$refs.appForm.validate(valid => {
        if (valid) {
          let cityindex = this.citys.findIndex(item => {
            return item.adcode === this.editingApp.cityadcode;
          });
          let city = this.citys[cityindex];
          console.log(city);
          if (city) {
            this.editingApp.cityname = city.name;
            this.editingApp.citycenter = city.center;
          }

          this.$http
            .post("/WechatMallOss/App/SaveAppInfo", this.editingApp)
            .then(response => {
              if (response.data.isSuccess) {
                this.$message({
                  message: "保存成功!",
                  type: "success"
                });
                if (response.data.appinfo) {
                  let updateIndex = this.gridDataSource.findIndex(app => {
                    if (app.basicinfo) {
                      return (
                        app.basicinfo.appid ===
                        response.data.appinfo.basicinfo.appid
                      );
                    } else {
                      return false;
                    }
                  });
                  if (updateIndex > -1) {
                    this.gridDataSource.splice(
                      updateIndex,
                      1,
                      response.data.appinfo
                    );
                  } else {
                    this.gridDataSource.push(response.data.appinfo);
                  }
                }
                this.show = false;
              } else {
                this.$message({
                  message: "数据提交出现错误,请稍后重试!",
                  type: "error"
                });
              }
            })
            .catch(() => {
              this.$message({
                message: "数据提交出现错误,请稍后重试!",
                type: "error"
              });
            });
        } else {
          return false;
        }
      });
    },
    /** 级联下拉框清空  */
      emtyCity() {
      this.editingApp.cityadcode = "";
    },
    selectProvince() {
      this.$http.get("/WechatMallOss/App/GetAllCitys").then(response => {
            if (response.data.isSuccess) {
              this.mapCategorys = response.data.mapCategorys;
            }
          });
    },
    uploadQrcodeSuccesss(res, file) {
      if (res.isSuccess && res.savedObjects) {
        this.editingApp.crmqrcodeurl =
          axios.defaults.baseURL +
          "/img/get?img=" +
          res.savedObjects[0].fileName;
      }
    },
    uploadSuccess(res, file) {
      if (res.isSuccess && res.savedObjects) {
        this.editingApp.swipepics.push(
          axios.defaults.baseURL +
            "/img/get?img=" +
            res.savedObjects[0].fileName
        );
      }
    },
    /** 添加快速备注信息  */
    addRemarks() {
      this.editingApp.fixedremarks.push({
        remarkstext: ""
      });
    }
  },
  computed: {
    uploadUrl() {
      let jwt = Utils.GetLocalData("zillionossjwt");
      return axios.defaults.baseURL + "/img/upload?token=" + jwt;
    }
  },
  watch: {
    show() {
      this.visible = this.show;
    },
    selectedProvince(value) {
      if (this.mapCategorys[value]) {
        let citys = this.mapCategorys[value].citys;
        this.citys = citys;
      } else {
        this.citys = [];
      }
    }
  }
};

</script>